import React, { useEffect, useState } from 'react';
import { useParams } from 'umi';
import { Card, Select, Button, message, Spin, Tabs } from 'antd';
import { getProblemById } from '@/services/problem';
import { addSubmission, runSampleTest } from '@/services/submission';
import CodeEditor from '@/services/CodeEditor';
import { getSampleTestCases } from '@/services/testcase';
import type { Problem, ResultVOProblem, Submission, TestCaseVO1 } from '@/types/openapi';
import { Modal } from 'antd';


const { Option } = Select;
const { TabPane } = Tabs;
const defaultTemplates: Record<string, string> = {
  cpp: `#include <iostream>
using namespace std;

int main() {
    // 请在此编写你的代码
    return 0;
}`,
  java: `import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 请在此编写你的代码
    }
}`,
  python: `# 请在此编写你的代码
def main():
    pass

if __name__ == "__main__":
    main()`
};

const ProblemPage: React.FC = () => {
  const [running, setRunning] = useState(false);
  const [runResult, setRunResult] = useState<Submission[]>([]);
  const { id } = useParams<{ id: string }>();
  const [problem, setProblem] = useState<Problem>();
  const [loading, setLoading] = useState(true);
  const [code, setCode] = useState('');
  const [language, setLanguage] = useState<'cpp' | 'java' | 'python'>('cpp');
  const [submitting, setSubmitting] = useState(false);
  const [testCases, setTestCases] = useState<TestCaseVO1[]>([]);
  const [selectedCaseIdx, setSelectedCaseIdx] = useState(0);
  const [selectedResultIdx, setSelectedResultIdx] = useState(0);



  const fetchProblem = async () => {
    setLoading(true);
    try {
      const res: ResultVOProblem = await getProblemById(Number(id));
      if (res.code === 200) {
        setProblem(res.data);
      } else {
        message.error(res.message || '获取题目失败');
      }
    } catch (err) {
      message.error('请求失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchTestCases = async () => {
    try {
      const res = await getSampleTestCases(Number(id));
      if (res.code === 200) {
        setTestCases(res.data || []);
      }
    } catch {
      message.warning('获取测试用例失败');
    }
  };

  useEffect(() => {
    fetchTestCases();
  }, [id]);

  const handleRun = async () => {
    if (!code.trim()) return message.warning('请输入代码！');
    setRunning(true);
    const submission: Submission = {
      code,
      language,
      problem_id: id,
      submitter_user_id: 1,
    };
    try {
      const res = await runSampleTest(submission);
      if (res.code === 200) {
        //将结果列表传回
        setRunResult(res.data || []);
        message.success('运行成功');
      } else {
        message.error(res.message || '运行失败');
      }
    } catch (e) {
      message.error('运行异常');
    } finally {
      setRunning(false);
    }
  };


  const handleSubmit = async () => {
    if (!code.trim()) return message.warning('请输入代码！');
    setSubmitting(true);
    const submission: Submission = {
      code,
      language,
      problem_id: id,
      submitter_user_id: 1,
    };
    try {
      const res = await addSubmission(submission);
      if (res.code === 200) {
        message.success('提交成功！');
        Modal.info({
          title: (
            <span style={{ color: res.data?.status === 'ACCEPTED' ? 'green' : 'red' }}>
              提交结果
            </span>
          ),
          width: 600,
          content: (
            <div>
              <p>
                <b>提交状态：</b>
                <span style={{ color: res.data?.status === 'ACCEPTED' ? 'green' : 'red' }}>
                  {res.data?.status || '未知'}
                </span>
              </p>
              <p><b>用时：</b>{res.data?.timeUsed || '-'} s</p>
              <p><b>内存：</b>{res.data?.memoryUsed || '-'} MB</p>
              <p><b>输出：</b></p>
              <pre style={{ background: '#f7f7f7', padding: 8 }}>{res.data?.stdout || '(无输出)'}</pre>
            </div>
          ),
        });

      } else {
        message.error(res.message || '提交失败');
      }
    } catch (e) {
      message.error('请求失败');
    } finally {
      setSubmitting(false);
    }
  };

  useEffect(() => {
    fetchProblem();
  }, [id]);

  useEffect(() => {
    setCode(defaultTemplates[language]);
  }, [language]);

  return (
    <Card title={problem?.problemTitle || '加载中...'}>
      {loading ? (
        <Spin />
      ) : (
        <>
          <p>{problem?.problemDesc}</p>
          <p>时间限制: {problem?.timeLimit}</p>
          <p>内存限制: {problem?.memLimit}</p>

          <Select
            value={language}
            onChange={(val) => setLanguage(val as 'cpp' | 'java' | 'python')}
            style={{ width: 120, marginBottom: 10 }}
          >
            <Option value="cpp">C++</Option>
            <Option value="java">Java</Option>
            <Option value="python">Python</Option>
          </Select>

          <div style={{ display: 'flex', gap: '10px', marginBottom: 10 }}>
            <Button type="default" onClick={handleRun} loading={running} style={{ marginRight: 8 }}>
              运行
            </Button>
            <Button
              type="primary"
              onClick={handleSubmit}
              loading={submitting}
              disabled={submitting}
            >
              提交
            </Button>
          </div>

          <CodeEditor
            language={language}
            value={code}
            onChange={setCode}
            height="400px"
          />

          <div style={{ marginTop: 10, background: '#ffffff', borderRadius: 4, padding: 12 }}>
            <Tabs defaultActiveKey="result" style={{ marginTop: 20, background: '#fff', color: '#000' }}>
              <TabPane tab="测试结果" key="result">
                {runResult.length === 0 ? (
                  <div style={{ color: '#000', background: '#fff', padding: 10 }}>
                    请先执行代码
                  </div>
                ) : (
                  <>
                    {/* 切换按钮 */}
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 12 }}>
                      {runResult.map((item, idx) => (
                        <Button
                          key={idx}
                          type={selectedResultIdx === idx ? 'primary' : 'default'}
                          onClick={() => setSelectedResultIdx(idx)}
                        >
                          {item.status === 'ACCEPTED' ? (
                            <span style={{ color: 'green' }}>✔ Case {idx + 1}</span>
                          ) : (
                            <span style={{ color: 'red' }}>✘ Case {idx + 1}</span>
                          )}
                        </Button>
                      ))}
                    </div>

                    {/* 当前用例详细信息 */}
                    <div
                      style={{
                        background: '#fafafa',
                        border: '1px solid #eee',
                        borderRadius: 4,
                        padding: 12,
                        color: '#000',
                      }}
                    >
                      <p><b>输入：</b></p>
                      <pre>{runResult[selectedResultIdx].inputWrongAnswer}</pre>
                      <p><b>预期输出：</b></p>
                      <pre>{runResult[selectedResultIdx].expected}</pre>
                      <p><b>实际输出：</b></p>
                      <pre>
                        {(runResult[selectedResultIdx].stdout || '') +
                          (runResult[selectedResultIdx].error || '')}
                      </pre>
                      <p><b>状态：</b>{runResult[selectedResultIdx].status}</p>
                    </div>
                  </>
                )}
              </TabPane>

              <TabPane tab="测试用例" key="cases">
                {testCases.length === 0 ? (
                  <div style={{ color: '#000', background: '#fff', padding: 10 }}>暂无测试用例</div>
                ) : (
                  <>
                    {/* Tab按钮组 */}
                    <div style={{ display: 'flex', marginBottom: 12, flexWrap: 'wrap', gap: 8 }}>
                      {testCases.map((_, idx) => (
                        <Button
                          key={idx}
                          type={selectedCaseIdx === idx ? 'primary' : 'default'}
                          onClick={() => setSelectedCaseIdx(idx)}
                        >
                          Case {idx + 1}
                        </Button>
                      ))}
                    </div>

                    {/* 展示选中用例内容 */}
                    <div
                      style={{
                        background: '#fafafa',
                        border: '1px solid #eee',
                        borderRadius: 4,
                        padding: 12,
                        color: '#000',
                      }}
                    >
                      <p><b>输入：</b></p>
                      <pre>{testCases[selectedCaseIdx].inputData}</pre>

                      <p><b>期望输出：</b></p>
                      <pre>{testCases[selectedCaseIdx].outputData}</pre>
                    </div>
                  </>
                )}
              </TabPane>
            </Tabs>
          </div>
        </>
      )}
    </Card>
  );
};

export default ProblemPage;